<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form
          :inline="true"
          :model="formInline"
          ref="formInline"
          label-width="80px"
          size="small"
          class="form-flex-item"
        >
          <el-row :gutter="20">
            <el-col :xs="12" :sm="12" :md="10" :lg="10">
              <el-form-item :label="'검색'|language" prop="name">
                <el-input v-model="formInline.name" :placeholder="'검색어: 아이디, 담당자, 이메일, 휴대폰 번호, 코멘트'|language" @keyup.enter.native="handleSearch"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">{{'검색' | language}}</el-button>
                <el-button size="small" @click="resetForm('formInline')">{{'초기화' | language}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">코치</div>
            </div>
            <div class="main-table-toolbar-option">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                style="margin-right:5px"
                @click="confirmAddUser"
              >{{'추가' | language}}</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'다운로드'|language" placement="top">
                  <i
                    @click="downloadFile('/api/setting/user/index', '코치')"
                    class="el-icon-download"
                  ></i>
                </el-tooltip>
              </el-link>
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'초기화'|language" placement="top">
                  <i @click="getUserList()" class="el-icon-refresh-right"></i>
                </el-tooltip>
              </el-link>-->
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange"
              @sortChange="sortChange"
            >
              <template v-slot:status="slotProps">
                <el-tag
                  v-if="slotProps.callback.row.deleted_at"
                  type="danger"
                  effect="dark"
                  size="small"
                >강제탈퇴</el-tag>
                <el-tag v-else type="success" effect="dark" size="small">사용중</el-tag>
              </template>
              <template v-slot:coach_roles="slotProps">
                <div
                  style="margin-top:5px"
                  v-for="item in slotProps.callback.row.coach_roles.split(',')"
                  :key="item"
                  type="success"
                  effect="dark"
                  size="small"
                >{{item}}</div>
              </template>
              <template v-slot:type="slotProps">
                <el-dropdown
                  trigger="click"
                  @command="(e) => updateStatus(e,slotProps.callback.row)"
                >
                  <span
                    class="el-dropdown-link"
                    :style="{color:slotProps.callback.row.status === 1 ? '#1890ff' : '#909399'}"
                  >
                    {{slotProps.callback.row.status === 1 ? "업무중" : "휴식중"}}
                    <i
                      class="el-icon-arrow-down el-icon--right"
                    ></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="1">업무중</el-dropdown-item>
                    <el-dropdown-item command="2">휴식중</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>

              <template v-slot:operation="slotProps">
                <el-button
                  @click.native.prevent="handleEdit(slotProps.callback.row)"
                  type="text"
                >{{ '수정' | language}}</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-popconfirm
                  title="정말로 복구 하시겠습니까?"
                  @onConfirm="handleRe(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="slotProps.callback.row.deleted_at"
                    type="text"
                  >{{'복구'| language}}</el-button>
                </el-popconfirm>
                <el-popconfirm
                  title="정말 강제 탈퇴 하시겠습니까?"
                  @onConfirm="handleDeleteUser(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="!slotProps.callback.row.deleted_at"
                    type="text"
                    style="color:#ff4949"
                  >강제탈퇴</el-button>
                </el-popconfirm>
                <el-popconfirm
                  :title="!slotProps.callback.row.deleted_at?'삭제하시겠습니까?':'코치정보를 삭제하시면, 더 이상 사용이 불가합니다.'"
                  @onConfirm="handleDeleteUser(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    slot="reference"
                    v-show="slotProps.callback.row.deleted_at"
                    type="text"
                    style="padding-left:15px;color:#f56c6c"
                  >{{ '삭제' | language}}</el-button>
                </el-popconfirm>
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogForm.title"
      custom-class="dialog-content"
      :visible.sync="dialogForm.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="550px"
      :close-on-click-modal="false"
    >
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          @handleEventChange="handleEventChange"
          :list-type-info="listTypeInfo"
        ></form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogForm.dialogVisible = false">취소</el-button>
        <el-button size="small" type="primary" @click="handleSubmitUser">확인</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDictData } from '@/api/app'
import { publicEvents } from '@/mixins'
import { mergeObjOfValue, deepClone, filterStr } from '@/utils'
import FormPage from '_c/FormPage'
import myTable from '_c/Table'
import * as userApi from '@/api/setting/user'
import * as roleApi from '@/api/setting/role'
const formInfoData = {
  id: '',
  name: '',
  full_name: '',
  phone: '',
  email: '',
  remark: '',
  password: '',
  password_confirmation: '',
  coach_roles: ''
}
const validateEMail = (rule, value, callback) => {
  // eslint-disable-next-line
  const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('정확한 우편함을 입력해 주십시오.'))
    } else {
      callback()
    }
  }
}
export default {
  name: 'setting-user',
  data () {
    return {
      formInline: {
        name: ''
      },
      options: [],
      columns: [{
        label: '상태',
        prop: '',
        width: 110,
        slot: 'status',
        sortable: true
      }, {
        label: '업무 여부',
        prop: '',
        width: 120,
        slot: 'type',
        sortable: true
      }, {
        label: '아이디',
        prop: 'name',
        sortable: true
      }, {
        label: '담당자',
        prop: 'full_name',
        sortable: true
      }, {
        label: '이메일',
        prop: 'email',
        sortable: true
      }, {
        label: '휴대폰 번호',
        prop: 'phone',
        sortable: true
      }, {
        label: '코멘트',
        prop: 'remark',
        sortable: true
      }, {
        label: '담당 코칭 서비스',
        prop: '',
        slot: 'coach_roles',
        width: 160,
        sortable: true
      }, {
        label: '등록시간',
        prop: 'created_at',
        width: 160,
        sortable: true
      }, {
        label: '최근활동시간',
        prop: 'lastlogin_at',
        width: 160,
        sortable: true
      }, {
        label: '관리',
        prop: '',
        width: 160,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogForm: {
        dialogVisible: false,
        title: '추가'
      },
      listTypeInfo: {
        role_id: [],
        CoachingService: []
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '아이디', value: 'name', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '담당 코칭 서비스', value: 'coach_roles', width: '260', type: 'cascader', className: 'el-form-block', list: 'CoachingService', props: { multiple: true }, required: true },
          { label: '담당자', value: 'full_name', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '이메일', value: 'email', width: '260', type: 'input', className: 'el-form-block', validator: validateEMail },
          { label: '연락처', placeholder: '\' - \' 는 빼고 입력해주세요', value: 'phone', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '코멘트', value: 'remark', width: '260', type: 'input', className: 'el-form-block' },
          { label: '새 비밀번호', value: 'password', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '비밀번호 확인', value: 'password_confirmation', width: '260', type: 'input', className: 'el-form-block', required: true, event: 'changePasswordConfirmation' }
        ],
        rules: {},
        labelWidth: '150px'
      },
      sortParams: {}
    }
  },
  components: {
    myTable,
    FormPage
  },
  mixins: [publicEvents],
  mounted () {
    this.formInfo.data = deepClone(formInfoData)
    this.getUserList()
    this.getRoleList()
    this.initRules()
    this.getCoachingService('CoachingService')
  },
  methods: {
    initRules () {
      const formInfo = this.formInfo
      formInfo.rules = this.$initRules(formInfo.fieldList)
    },
    getRoleList () {
      roleApi.getRoleList().then(res => {
        this.options = this.listTypeInfo.role_id = res.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
      })
    },
    getUserList () {
      const data = {
        ...this.formInline,
        is_instructor: 1,
        ...this.sortParams,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      userApi.getUserList(data).then(res => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      }).catch(() => {
        this.loading = false
      })
    },
    getCoachingService (key) {
      getDictData(key).then(res => {
        this.listTypeInfo[key] = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx)
          }
        })
      })
    },
    sortChange (val) {
      this.pagination.currentPage = 1
      if (val.order === 'ascending') {
        this.sortParams = {
          sort: 'asc',
          order_by: val.prop
        }
      } else if (val.order === 'descending') {
        this.sortParams = {
          sort: 'desc',
          order_by: val.prop
        }
      } else {
        this.sortParams = {}
      }
      this.getUserList()
    },
    handleRe (id) {
      userApi.reUser({ id }).then(res => {
        this.getUserList()
      })
    },
    handleDeleteUser (id) {
      userApi.deleteUser({ id }).then(res => {
        this.getUserList()
      })
    },
    updateStatus (e, row) {
      userApi.updateStatus({ status: e, user_id: row.id }).then(res => {
        this.getUserList()
      })
    },
    confirmAddUser () {
      this.dialogForm.title = '추가'
      mergeObjOfValue(this.formInfo.data, formInfoData)
      this.dialogForm.dialogVisible = true
    },
    handleSubmitUser () {
      const data = {
        ...this.formInfo.data
      }
      if (data.coach_roles.length === 0) return this.$message.error('담당 코칭서비스를 선택해주세요.')
      this.formInfo.data.phone = filterStr(this.formInfo.data.phone)
      if (Array.isArray(data.coach_roles)) {
        this.formInfo.data.coach_roles = data.coach_roles.join()
      }
      if (data.password !== '') {
        if (data.password === data.password_confirmation) {
          if (this.formInfo.data.id) {
            userApi.updateUser({ ...this.formInfo.data, role_id: 0, is_instructor: 1 }).then(res => {
              this.$message({
                message: '반영이 완료되었습니다.',
                type: 'success'
              })
              this.dialogForm.dialogVisible = false
              this.getUserList()
              this.formInfo.data = deepClone(formInfoData)
            })
          } else {
            userApi.ceaterUser({ ...this.formInfo.data, role_id: 0, is_instructor: 1 }).then(res => {
              this.$message({
                message: '추가되었습니다.',
                type: 'success'
              })
              this.dialogForm.dialogVisible = false
              this.formInfo.data = deepClone(formInfoData)
              this.getUserList()
            })
          }
        }
      } else {
        delete data.password
        delete data.password_confirmation
        if (this.formInfo.data.id) {
          userApi.updateUser({ ...this.formInfo.data, role_id: 0, is_instructor: 1 }).then(res => {
            this.$message({
              message: '반영이 완료되었습니다.',
              type: 'success'
            })
            this.dialogForm.dialogVisible = false
            this.getUserList()
            this.formInfo.data = deepClone(formInfoData)
          })
        } else {
          userApi.ceaterUser({ ...this.formInfo.data, role_id: 0, is_instructor: 1 }).then(res => {
            this.$message({
              message: '추가되었습니다.',
              type: 'success'
            })
            this.dialogForm.dialogVisible = false
            this.formInfo.data = deepClone(formInfoData)
            this.getUserList()
          })
        }
      }
    },
    handleEdit (rowData) {
      const data = { ...rowData }
      const arr = []
      this.listTypeInfo.CoachingService.forEach((item) => {
        if (data.coach_roles.indexOf(item.label) > -1) {
          arr.push(item.value)
        }
      })
      data.coach_roles = arr
      this.dialogForm.title = '수정'
      this.formInfo.data.id = rowData.id
      mergeObjOfValue(this.formInfo.data, data)
      this.formInfo.data.password = ''
      this.formInfo.data.password_confirmation = ''
      this.dialogForm.dialogVisible = true
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getUserList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getUserList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getUserList()
    },
    handleEventChange (event, data) {
      switch (event) {
        case 'changePasswordConfirmation': {
          if (this.formInfo.data.password === '') {
            this.$message({
              message: '새로운 비밀번호를 입력해주세요.',
              type: 'warning'
            })
            this.formInfo.data.password_confirmation = ''
          } else if (this.formInfo.data.password !== this.formInfo.data.password_confirmation) {
            this.$message({
              message: '비밀번호와 비밀번호 확인이 다릅니다.',
              type: 'error'
            })
            this.formInfo.data.password_confirmation = ''
          }
          break
        }
      }
    }
  }
}
</script>
